package airthmetic.exercise.dp;

public class _121_买卖股票的最佳时机 {

    //非动态规划写法
    public static int maxProfit3(int[] prices) {
        int min=prices[0];
        int max=0;
        for(int price : prices){
           if(price < min){
               min = price;
           }else{
               max =  Math.max(max, price-min);
           }
       }
        return max;
    }

    public static int maxProfit(int[] prices) {
        int n = prices.length;
        int[][] dp = new int[n][2];
        for(int i=0; i<n; i++){
            if(i==0){
                dp[i][0] = 0;
                dp[i][1] =-prices[i];
                continue;
            }
            dp[i][0] = Math.max(dp[i-1][1] +prices[i], dp[i-1][0]);
            dp[i][1] = Math.max(-prices[i] , dp[i-1][1]);
        }
        return dp[n-1][0];
    }

    // 状态压缩
    // 因为求解dp[i][0] 和dp[i][1]只用到上一层元素。故压缩到O(1)复杂度两个变量
    public static int maxProfit2(int[] prices) {
        int n = prices.length;
        int i_0 = 0;
        int i_1 = Integer.MIN_VALUE;

        for(int i=0; i<n; i++){
            i_0 = Math.max(i_1 +prices[i], i_0);
            i_1 = Math.max(-prices[i] ,i_1);
        }
        return i_0;
    }


    public static void main(String[] args) {
        int[] prices  = new int[]{7,1,5,3,6,4};
        System.out.println(maxProfit3(prices));
        System.out.println(maxProfit(prices));
    }
}
